package com.kyzh.core.pager.weal.accountbuy

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProviders
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.gushenge.atools.util.setHeight
import com.gushenge.core.base.Base
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.Deal
import com.gushenge.core.dao.GlobalKeys
import com.kyzh.core.R
import com.kyzh.core.activities.BaseFragmentActivity
import com.kyzh.core.activities.BrowserActivity
import com.kyzh.core.adapters.GameDetailDealAdapter
import com.kyzh.core.databinding.FragmentDealProductDetailBinding
import com.kyzh.core.uis.alert
import com.kyzh.core.utils.*
import com.kyzh.core.viewmodel.DealProductDetailViewModel
import kotlinx.android.synthetic.main.fragment_deal_product_detail.*
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast

class DealProductDetailFragment(val id: String) : BaseFragment() {
    private lateinit var context: Activity
    private lateinit var viewModel: DealProductDetailViewModel
    private var loading: AlertDialog? = null
    private lateinit var binding: FragmentDealProductDetailBinding
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_deal_product_detail, container, false)

        viewModel = ViewModelProviders.of(this).get(DealProductDetailViewModel::class.java)
        binding.vm = viewModel
        binding.lifecycleOwner = this
        return binding.root

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        context = requireActivity()
        loading = loading()
        titleView.setOnMoreOnClickListener {
            startActivity<BrowserActivity>(GlobalKeys.TITLE to getString(R.string.serviceCenter), GlobalKeys.LINK to Base.BASEURL + "/?ct=app&ac=problem")
        }

        initData()
    }

    @SuppressLint("SetTextI18n")
    private fun initData() {
        viewModel.setId(id)
        viewModel.refresh()
        viewModel.error().observe(viewLifecycleOwner) {
            loading?.dismiss()
            alert(getString(R.string.pleaseNote), it, getString(R.string.reload), null,{
                viewModel.refresh()
            },{})
        }
        viewModel.toast().observe(viewLifecycleOwner) {
            toast(it)
        }
        viewModel.getData().observe(viewLifecycleOwner) {
            loading?.dismiss()
            it.apply {
                tvTime.text = "${getString(R.string.addedTime)}: $create_time"
                tvSystem.text = "${getString(R.string.system)}: ${if (system == 1) "Android" else "iOS"}"
                tvAccountName.text = "${getString(R.string.accountName)}: $role_name "
                tvServer.text = "${getString(R.string.accountServer)}: $sname"
                tvAccountDesc.text = String.format(getString(R.string.accountDescInfo) , regday,pay_money)
                if (shop_ok == "1") {
                    ivDealReview.visibility = View.GONE
                    start.setBackgroundColor(Color.parseColor("#D8D8D8"))
                    tvAccountDesc.setBackgroundColor(resources.getColor(R.color.bg_f5))
                    start.text = getString(R.string.rolesSold)
                } else {
                    ivDealReview.visibility = View.VISIBLE
                    start.setBackgroundColor(resources.getColor(R.color.colorAccent))
                    tvAccountDesc.setBackgroundColor(Color.parseColor("#fde6d3"))
                    start.text = getString(R.string.buyNow)
                }
                tvPrice.text = "¥${money}"
                tvRegTime.text = String.format(getString(R.string.registeredDays),sellerinfo.regday)
                tvSelling.text = String.format(getString(R.string.selling),sellerinfo.selling)
                tvSold.text = String.format(getString(R.string.sold),sellerinfo.soldout)
                rvImages.setHeight( dip(133) * images.size)
                rvOthers.setHeight( dip(86) * other.size)

                rvImages.layoutManager = object : LinearLayoutManager(context) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }

                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                rvOthers.layoutManager = object : LinearLayoutManager(context) {
                    override fun canScrollHorizontally(): Boolean {
                        return false
                    }

                    override fun canScrollVertically(): Boolean {
                        return false
                    }
                }
                rvImages.adapter = ImageAdapter(R.layout.simple_image_item_1, images)
                rvOthers.adapter = GameDetailDealAdapter(R.layout.game_detail_deal_item, other)
                btGameDetail.setOnClickListener {
                    startGameDetailActivity(gid)
                }
                start.setOnClickListener {
                    if (startLogin()) {
                        if (shop_ok == "1") {
                            toast(getString(R.string.rolesSold))
                        } else {
                            if(images==null ||images.size==0){
                                startActivity<BaseFragmentActivity>(
                                    GlobalKeys.TYPE to BaseFragmentActivity.SETTLE,
                                    GlobalKeys.KEY to Deal("", id, "", introduction, money, name, create_time, "", "", "", "")
                                )
                            }else{
                                startActivity<BaseFragmentActivity>(
                                    GlobalKeys.TYPE to BaseFragmentActivity.SETTLE,
                                    GlobalKeys.KEY to Deal("", id, images[0], introduction, money, name, create_time, "", "", "", "")
                                )
                            }
                        }
                    }

                }
                collect.setOnClickListener {
                    viewModel.collect()
                }
                share.setOnClickListener {
                    shareWeb(name, introduction, images[0], "${Base.BASEURL}/?ct=trade&ac=info&id=${id}")
                }
            }
        }


        viewModel.getCollect().observe(viewLifecycleOwner) {
            if (it) {
                collect.setImageResource(R.drawable.game_xq_collect_true)
            } else {
                collect.setImageResource(R.drawable.game_xq_collect_false)
            }
        }
    }


    private inner class ImageAdapter(layout: Int, val beans: ArrayList<String>) : BaseQuickAdapter<String, BaseViewHolder>(layout, beans) {
        override fun convert(helper: BaseViewHolder, item: String) {
            item?.apply {
                Glide.with(context).load(this).into(helper.getView(R.id.image))
                helper.itemView.setOnClickListener {
                    context.reviewImages(beans, helper.adapterPosition)
                }
            }
        }
    }
}